package com.thinkingcoder.common.http;

import com.thinkingcoder.common.util.HttpUtils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

@Slf4j
public class OkHttpInvoker implements HttpUtils {

    private final static MediaType JSON_TYPE = MediaType.get("application/json; charset=utf-8");

    private OkHttpClient client;

    public OkHttpInvoker(HttpProperties httpProperties) {
        this.client = new OkHttpClient.Builder()
            .connectionPool(new ConnectionPool(httpProperties.getMaxIdleConnections(),
                httpProperties.getKeepAliveDuration(), httpProperties.getTimeUnit()))
            .connectTimeout(httpProperties.getConnectTimeout(), httpProperties.getTimeUnit())
            .readTimeout(httpProperties.getReadTimeout(), httpProperties.getTimeUnit())
            .writeTimeout(httpProperties.getWriteTimeout(), httpProperties.getTimeUnit()).build();
    }

    @Override
    public String get(String url) {
        log.debug("get ===> url : {}", url);
        Request request = new Request.Builder().url(url).get().build();
        try {
            String responseJson = client.newCall(request).execute().body().string();
            log.debug("get ===> response : {}", responseJson);
            return responseJson;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String post(String url, String body) {
        log.debug("post ===> url : {} , body : {}", url, body);
        Request request = new Request.Builder().url(url).post(RequestBody.create(body, JSON_TYPE)).build();

        try {
            String responseJson = client.newCall(request).execute().body().string();
            log.debug("post ===> response : {}", responseJson);
            return responseJson;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
